import string
import random
import screen_text
import process_input
from process_input import ResultTuple

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api.labs import taskqueue

# global variables
# use to control the maximum number of characters appended to the second document
max_length = 3
# use to control the length of the keys used for each request
key_length = 10
# use to store the current request id
request_id = ""
# array of all "starting" characters, uppercase letters, lowercase letters, digits, punctation, space character
# length of char_array = 95 (includes the space character)
char_array = ["0",  "1",  "2",  "3",  "4",  "5",  "6",  "7",  "8",  "9",  "a",  "b",  "c",  "d",  "e",  "f",  "g",  "h",  "i",  "j",  "k",  "l",  "m",  "n",  "o",  "p",  "q",  "r",  "s",  "t",  "u",  "v",  "w",  "x",  "y",  "z",  "A",  "B",  "C",  "D",  "E",  "F",  "G",  "H",  "I",  "J",  "K",  "L",  "M",  "N",  "O",  "P",  "Q",  "R",  "S",  "T",  "U",  "V",  "W",  "X",  "Y",  "Z",  "!",  "\"",  "#",  "$",  "%",  "&",  "'",  "(",  ")",  "*",  "+",  ",",  "-",  ".",  "/",  ":",  ";",  "<",  "=",  ">",  "?",  "@",  "[",  "\\",  r"]",  "^",  "_",  "`",  r"{",  r"|",  r"}",  "~",  " "]

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write(screen_text.getMainPage())

class InputText1(webapp.RequestHandler):
    def post(self):
		global char_array, request_id, key_length
		document1 = self.request.get('doc1')
		document2 = self.request.get('doc2')
		request_id = "".join([random.choice(string.letters + string.digits) for x in range(key_length)])
		for i in range(0, len(char_array)):
			taskqueue.Queue('search').add(taskqueue.Task(url='/performsearch', 
														params={'requestID': request_id, 
														'document1': document1, 
														'document2': document2,
														'startString': char_array[i]}))		
		# go to page that will display output
		self.response.out.write(screen_text.getPreFinalOutput(request_id, len(char_array)))
		#self.redirect('/finaloutput')
		
class FinalOutput(webapp.RequestHandler):
	def get(self):
		request_id = self.request.get('requestID')
		currentData = db.GqlQuery("SELECT * FROM ResultTuple WHERE request_id = :rid ORDER BY bit_diff, finish_time", rid=request_id)
		self.response.out.write(screen_text.getFinalOutput(request_id, len(char_array) , currentData))
	
class PerformSearch(webapp.RequestHandler):
	def post(self):
		global max_length #, requestID
		requestID = self.request.get('requestID')
		doc1 = self.request.get('document1')
		doc2 = self.request.get('document2')
		startString = self.request.get('startString')
		process_input.performSearch(doc1, doc2, requestID, startString, max_length)
		
class DataStore(webapp.RequestHandler):
	def get(self):
		resultTuples = ResultTuple.all()
		self.response.out.write(screen_text.getDataStore(resultTuples))
		
class ClearDataStore(webapp.RequestHandler):
	def get(self):
		resultTuples = ResultTuple.all()
		for tuple in resultTuples:
			db.delete(tuple)
		self.response.out.write("""<html>Data store now contains no data.</html>""")

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/InputText1', InputText1), 
									  ('/datastore', DataStore),
									  ('/finaloutput', FinalOutput),
									  ('/performsearch', PerformSearch),
									  ('/cleardatastore', ClearDataStore)],
                                     debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
    main()
